package com.ct.ecommerce.goods.controller;

import com.ct.ecommerce.api.goods.client.GoodsService;
import com.ct.ecommerce.api.goods.dto.GoodsDTO;
import com.ct.ecommerce.api.goods.dto.GoodsQueryDTO;
import com.ct.ecommerce.framework.core.BeanCopierUtils;
import com.ct.ecommerce.framework.core.response.PageUI;
import com.ct.ecommerce.framework.core.response.R;
import com.ct.ecommerce.framework.security.SecurityContextHolderUtils;
import com.ct.ecommerce.goods.vo.handle.GoodsQueryVO;
import com.ct.ecommerce.goods.vo.view.GoodsVO;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author changtong
 * @since 2021/5/19
 */
@RestController
@RequestMapping("/goods")
@Slf4j
public class GoodsController {

    @Resource
    private GoodsService goodsService;

    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('goods:view')")
    public R<GoodsVO> findGoodsById(@PathVariable("id") Long goodsId) {
        try {
            GoodsDTO goods = goodsService.findGoodsById(goodsId);
            GoodsVO g = BeanCopierUtils.copyProperties(goods, GoodsVO.class);
            log.info("userInfo => {}", SecurityContextHolderUtils.getUser());
            return R.ok(g);
        } catch (Exception e) {
            log.error("查询商品出错 : ", e);
            return R.fail("查询商品出错...");
        }
    }

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('goods:view')")
    public R<PageUI<GoodsVO>> findGoods(GoodsQueryVO params) {
        try {
            GoodsQueryDTO query = BeanCopierUtils
                .copyProperties(params, GoodsQueryDTO.class);
            PageUI<GoodsDTO> page = goodsService.findGoodsPage(query);
            PageUI<GoodsVO> rs = new PageUI<>();
            rs.setPage(page.getPage())
                .setRows(page.getRows())
                .setTotal(page.getTotal())
                .setRecords(
                    BeanCopierUtils.copyPropertiesOfList(page.getRecords(), GoodsVO.class)
                );
            return R.ok(rs);
        } catch (Exception e) {
            log.error("查询商品列表出错 : ", e);
            return R.fail("查询商品列表出错...");
        }
    }


}
